<?php  defined('BASEPATH') OR exit('No direct script access allowed');

class Dailyplans extends Admin_Controller {

	private $_validation_rules = array(
		array(
				'field'	=> 'tour_id',
				'label'	=> 'lang:dailyplans.tour_id',
				'rules'	=> 'required'
		),
		array(
				'field'	=> 'departure_city_id',
				'label'	=> 'lang:dailyplans.departure_city_id',
				'rules'	=> 'required'
		),
		array(
				'field'	=> 'destination_city_id',
				'label'	=> 'lang:dailyplans.destination_city_id',
				'rules'	=> 'required'
		),
		array(
				'field'	=> 'hotel_id',
				'label'	=> 'lang:dailyplans.hotel_id',
				'rules'	=> 'required'
		),
		array(
				'field'	=> 'day',
				'label'	=> 'lang:dailyplans.day',
				'rules'	=> 'optional'
		),
		array(
				'field'	=> 'attraction_id',
				'label'	=> 'lang:dailyplans.attraction_id',
				'rules'	=> 'optional'
		),
		array(
				'field'	=> 'attraction_id',
				'label'	=> 'lang:dailyplans.attraction_id',
				'rules'	=> 'optional'
		),
		array(
				'field'	=> 'city_id',
				'label'	=> 'lang:dailyplans.city_id',
				'rules'	=> 'optional'
		),
		array(
				'field'	=> 'image',
				'label'	=> 'lang:dailyplans.image',
				'rules'	=> 'optional|numeric'
		),
		array(
				'field'	=> 'pickuppoint_id',
				'label'	=> 'lang:dailyplans.pickuppoint_id',
				'rules'	=> 'optional'
		)
	);
	public function __construct()
	{
		parent::__construct();
		$this->lang->load('dailyplans/dailyplans');
		$this->load->model('dailyplans/dailyplans_model', 'dailyplans_m');
		
		$this->load->library('form_validation');
		$this->load->helper('ckeditor');
		$supported_languages = $this->config->item('supported_languages');
		foreach($supported_languages as $language => $lang_content){
			if(CURRENT_LANGUAGE == $language){
				$rules = 'required';
			}else{
				$rules = 'optional';
			}
			$this->_validation_rules[] = array(
					'field'	=> 'name_'. $language,
					'label'	=> 'lang:dailyplans.name_label',
					'rules'	=> $rules. '|max_length[255]'
			);
			$this->_validation_rules[] = array(
					'field'	=> 'detail_'. $language,
					'label'	=> 'lang:dailyplans.detail',
					'rules'	=> $rules. '|max_length[2000]'
			);
			$this->_validation_rules[] = array(
					'field'	=> 'tips_'. $language,
					'label'	=> 'lang:dailyplans.tips',
					'rules'	=> $rules. '|max_length[2000]'
			);
		}
		$tour_id = $this->uri->segment(4);
		$this->form_validation->set_rules($this->_validation_rules);
		array_unshift($this->shortcuts, 
				array('name' => lang('menu_2_catalog_dailyplans'), 'link' => site_url('admin/catalog/dailyplans/'. $tour_id)),
				array('name' => lang('menu_2_catalog_create_dailyplan'), 'link' => site_url('admin/catalog/create_dailyplan/'. $tour_id)),
				array('name' => lang('menu_2_catalog_tours'), 'link' => site_url('admin/catalog/tours')),
				array('name' => lang('menu_2_catalog_create_tour'), 'link' => site_url('admin/catalog/create_tour'))
		);

		$this->load->model('regions/regions_model', 'regions_m');
		$this->load->model('hotels/hotels_model', 'hotels_m');
		$this->load->model('attractions/attractions_model', 'attractions_m');
		$this->load->model('pickuppoints/pickuppoints_model', 'pickuppoints_m');
		
		$this->load->model('dailyplans/dailyattractions_model', 'dailyattractions_m');
		$this->load->model('dailyplans/dailypickuppoints_model', 'dailypickuppoints_m');
		$this->load->model('dailyplans/dailyroute_model', 'dailyroute_m');
		
		$this->attractions = $this->attractions_m->get_lang_list(FALSE, CURRENT_LANGUAGE);
		$this->cities = $this->regions_m->get_lang_list(array('region_type' => 3), CURRENT_LANGUAGE);
		$this->hotels = $this->hotels_m->get_lang_list(FALSE, CURRENT_LANGUAGE);
		$this->pickuppoints = $this->pickuppoints_m->get_lang_list(FALSE, CURRENT_LANGUAGE);
		
		$this->load->model('tours/tours_model', 'tours_m');
		$tour = $this->tours_m->get($tour_id);
		if ( ! $tour)
		{
			redirect('admin/catalog/tours');
		}
		$tour_lang = $this->tours_m->get_lang(array('id' => $tour_id));
		$tour->langs = fetch_lang($tour_lang);
		$this->template->set_data(array(
				'shortcuts' => $this->shortcuts,
				'cities' => $this->cities,
				'tour' => $tour,
				'attractions' => $this->attractions,
				'pickuppoints' => $this->pickuppoints,
				'hotels' => $this->hotels
		));
	}

	// ------------------------------------------------------------------------

	public function index($tour_id)
	{
		$dailyplans = $this->dailyplans_m->get_lang_list(array('tour_id' => intval($tour_id), 'order_by' => 'day'), CURRENT_LANGUAGE);
		$this->template->load('dailyplans/list', array(
			'dailyplans' => $dailyplans
		));
	}

	// ------------------------------------------------------------------------

	/**
	 * Checks if the element save process can be done.
	 *
	 * @returns		Boolean		True if the save can be done, false if not
	 *
	 */
	function _check_before_save()
	{
		$default_lang = Settings_lib::get('site_lang');
		$default_lang_name = $this->input->post('name_'.$default_lang);
	
		if ($default_lang_name == FALSE)
		{
			return FALSE;
		}
	
		return TRUE;
	}
	
	// ------------------------------------------------------------------------
	
	public function create($tour_id)
	{
		if(empty($tour_id)){
			redirect('admin/catalog/rours');
		}
		if ($this->form_validation->run())
		{
			if ($this->_check_before_save() == TRUE)
			{
				list($data, $lang_data) = $this->_prepare_data($this->dailyplans_m->get_table());
				$dailyplan_id = $this->dailyplans_m->save($data, $lang_data);
				
				if($dailyplan_id){
					
					$attraction_id = $this->input->post('attraction_id');
					$city_id = $this->input->post('city_id');
					$pickuppoint_id = $this->input->post('pickuppoint_id');
					
					if(!empty($attraction_id)){
						$attraction_id = array_unique($attraction_id);
						foreach($attraction_id as $aid){
							$this->dailyattractions_m->insert(array('daily_plan_id' => $dailyplan_id, 'attraction_id' => $aid), TRUE);
						}
					}
					if(!empty($city_id)){
						$city_id = array_unique($city_id);
						foreach($city_id as $cid){
							$this->dailyroute_m->insert(array('daily_plan_id' => $dailyplan_id, 'city_id' => $cid), TRUE);
						}
					}
					if(!empty($pickuppoint_id)){
						$pickuppoint_id = array_unique($pickuppoint_id);
						foreach($pickuppoint_id as $pid){
							$this->dailypickuppoints_m->insert(array('daily_plan_id' => $dailyplan_id, 'pickup_point_id' => $pid), TRUE);
						}
					}
					
					$message	= lang('dailyplans.create_success');
					$status		= 'success';
				}else{
					$message	= lang('dailyplans.create_error');
					$status		= 'error';
				}
				$dailyplan_count = $this->dailyplans_m->count_by('tour_id', $tour_id);
				$this->tours_m->update($tour_id, array('days' => $dailyplan_count));
				$this->session->set_flashdata($status, $message);
				redirect('admin/catalog/dailyplans/'. $tour_id);
			}
		}

		foreach ($this->_validation_rules as $rules)
		{
			if('attraction_id' == $rules['field']){
				$attraction_id = $this->input->post('attraction_id');
				$dailyplan->{$rules['field']} = empty($attraction_id)?array(): $this->input->post('attraction_id');
			}elseif('city_id' == $rules['field']){
				$city_id = $this->input->post('city_id');
				$dailyplan->{$rules['field']} = empty($city_id)?array(): $this->input->post('city_id');
			}elseif('pickuppoint_id' == $rules['field']){
				$pickuppoint_id = $this->input->post('pickuppoint_id');
				$dailyplan->{$rules['field']} = empty($pickuppoint_id)?array(): $this->input->post('pickuppoint_id');
			}else{
				$dailyplan->{$rules['field']} = set_value($rules['field']);
			}
		}
		$this->data['dailyplan'] = $dailyplan;
		$this->data['tour_id'] = intval($tour_id);
		$this->template->set('site_title', lang('dailyplans.create_title'))->load('dailyplans/create', $this->data);
	}

	// ------------------------------------------------------------------------

	public function edit($tour_id, $id = 0)
	{
		$dailyplan = $this->dailyplans_m->get($id);
		
		if ( ! $dailyplan)
		{
			redirect('admin/catalog/dailyplans');
		}
		$dailyplan_lang = $this->dailyplans_m->get_lang(array('id' => $id));
		$dailyplan->langs = fetch_lang($dailyplan_lang);
		
		if ($this->form_validation->run())
		{
			if ($this->_check_before_save() == TRUE)
			{
				list($data, $lang_data) = $this->_prepare_data($this->dailyplans_m->get_table());
				
				$dailyplan_id = $this->dailyplans_m->save($data, $lang_data);
	
				if($dailyplan_id){
					
					$attraction_id = $this->input->post('attraction_id');
					$city_id = $this->input->post('city_id');
					$pickuppoint_id = $this->input->post('pickuppoint_id');
					
					$this->dailyattractions_m->delete_by('daily_plan_id', $dailyplan_id);
					$this->dailyroute_m->delete_by('daily_plan_id', $dailyplan_id);
					$this->dailypickuppoints_m->delete_by('daily_plan_id', $dailyplan_id);
					
					if(!empty($attraction_id)){
						$attraction_id = array_unique($attraction_id);
						foreach($attraction_id as $aid){
							$this->dailyattractions_m->insert(array('daily_plan_id' => $dailyplan_id, 'attraction_id' => $aid), TRUE);
						}
					}
					if(!empty($city_id)){
						$city_id = array_unique($city_id);
						foreach($city_id as $cid){
							$this->dailyroute_m->insert(array('daily_plan_id' => $dailyplan_id, 'city_id' => $cid), TRUE);
						}
					}
					if(!empty($pickuppoint_id)){
						$pickuppoint_id = array_unique($pickuppoint_id);
						foreach($pickuppoint_id as $pid){
							$this->dailypickuppoints_m->insert(array('daily_plan_id' => $dailyplan_id, 'pickup_point_id' => $pid), TRUE);
						}
					}
					
					$message	= lang('dailyplans.create_success');
					$status		= 'success';
				}else{
					$message	= lang('dailyplans.create_error');
					$status		= 'error';
				}
			}
			$this->session->set_flashdata($status, $message);
			redirect('admin/catalog/dailyplans/'. $tour_id. '/'. $id);
		}
		$dailyplan->attraction_id = $this->dailyattractions_m->dailyplan_attractions($id);
		$dailyplan->city_id = $this->dailyroute_m->dailyplan_routes($id);
		$dailyplan->pickuppoint_id = $this->dailypickuppoints_m->dailyplan_pickuppoints($id);
		$this->data['dailyplan'] = $dailyplan;
		$this->data['tour_id'] = intval($tour_id);
		$this->template->set('site_title', sprintf(lang('dailyplans.edit_title'), def_lang($dailyplan, 'name')))->load('dailyplans/edit', $this->data);
	}

	// ------------------------------------------------------------------------

	public function delete($id = 0)
	{
		$ids = $id
			? is_array($id)
				? $id
				: array($id)
			: (array) $this->input->post('action_to');

		$total		= sizeof($ids);
		$deleted	= array();

		// Try do deletion
		foreach ($ids as $id)
		{
			// Get the row to use a value.. as title, name
			if ($dailyplan = $this->dailyplans_m->_get($id, CURRENT_LANGUAGE))
			{
				// Make deletion retrieving an status and store an value to display in the messages
				$deleted[($this->dailyplans_m->delete($id) ? 'success': 'error')][] = $dailyplan->name;
				
				$dailyplan_count = $this->dailyplans_m->count_by('tour_id', $dailyplan->tour_id);
				$this->tours_m->update($dailyplan->tour_id, array('days' => $dailyplan_count));
				
				$this->dailyattractions_m->delete_by('daily_plan_id', $dailyplan->id);
				$this->dailyroute_m->delete_by('daily_plan_id', $dailyplan->id);
				$this->dailypickuppoints_m->delete_by('daily_plan_id', $dailyplan->id);
			}
		}

		// Set status messages
		foreach ($deleted as $status => &$values)
		{
			// Mass deletion
			if (($status_total = sizeof($values)) > 1)
			{
				$last_value		= array_pop($values);
				$first_values	= implode(', ', $values);

				// Success / Error message
				$values = sprintf(lang('dailyplans.delete_mass_' . $status), $status_total, $total, $first_values, $last_value);
			}

			// Single deletion
			else
			{
				// Success / Error messages
				$values = sprintf(lang('dailyplans.delete_' . $status), $values[0]);
			}
		}

		// He arrived here but it was not done nothing, certainly valid ids not were selected
		if ( ! $deleted)
		{
			$status		= 'error';
			$deleted	= array('error' => lang('dailyplans.no_select_error'));
		}
		else
		{
			$status = array_key_exists('error', $deleted) ? 'error': 'success';
		}

		foreach ($deleted as $status => $message)
		{
			$this->session->set_flashdata($status, $message);
		}
		if(isset($dailyplan->tour_id)){
			redirect('admin/catalog/dailyplans/'. $dailyplan->tour_id);
		} else {
			redirect('admin/catalog/dailyplans');
		}		
	}

	// ------------------------------------------------------------------------

	public function action()
	{
		$action = strtolower($this->input->post('btnAction'));
		
		if ($action)
		{
			// Get the id('s)
			$id_array = $this->input->post('action_to');

			// Call the action we want to do
			if (method_exists($this, $action))
			{
				return $this->{$action}($id_array);
			}
		}

		redirect('admin/catalog/dailyplans');
	}
}
